package com.changgou.oauth.service.impl;

import com.changgou.oauth.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;
import java.util.Map;

/**
 * 描述
 *
 * @author ljh
 * @version 1.0
 * @package com.changgou.oauth.service.impl *
 * @Date 2019-12-4
 * @since 1.0
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Override
    public Map login(String username, String password, String grant_type, String clientId, String clientSecret) {
        ServiceInstance serviceInstance = loadBalancerClient.choose("user-auth");
        String oauthUrl = serviceInstance.getUri().toString()+"/oauth/token";
        //1.获取用户名和密码
        //2.设置clientid 和client secret
        //3.设置授权模式 grant_type 为密码模式(写死)

        //4.使用resttemplate来模拟(POSTman)发送请求 申请令牌信息

        //设置头信息 和 请求体信息

        MultiValueMap<String,String> body = new LinkedMultiValueMap<String,String>();
        body.add("grant_type",grant_type);
        body.add("username",username);
        body.add("password",password);
        MultiValueMap<String,String> headers = new LinkedMultiValueMap<String,String>();
        // '[{"key":"Authorization","value":"Basic Y2hhbmdnb3U6Y2hhbmdnb3U=","description":""}]'
        //  changgou12321:changgou123232
        headers.add("Authorization","Basic "+Base64.getEncoder().encodeToString(new String(clientId+":"+clientSecret).getBytes()));



        HttpEntity<MultiValueMap<String,String>> requestEntity = new HttpEntity<MultiValueMap<String,String>>(body,headers);


        ResponseEntity<Map> responseEntity = restTemplate.exchange(oauthUrl, HttpMethod.POST, requestEntity, Map.class);

        //5.返回
        Map responseBody = responseEntity.getBody();
        return responseBody;
    }

    public static void main(String[] args) {
        byte[] decode = Base64.getDecoder().decode("Y2hhbmdnb3UxMjMyMTpjaGFuZ2dvdTEyMzIzMg==");
        String s = new String(decode);
        System.out.println(s);
    }
}
